﻿using System.Collections.Generic ;
using System.Linq ;
using System.ServiceModel.DomainServices.Server ;
using System.Web.Security ;

namespace OpenLightGroup.Common.UserManagement.Web
    {
        public partial class UserManagementService : DomainService
            {

                [Query]
                public IEnumerable<Role> GetRoles ( )
                    {

                        var roles = from string r in System.Web.Security.Roles.GetAllRoles( )
                               select new Role { Name = r };

                        return roles.AsQueryable( ) ;

                    }

                [Delete]
                public void DeleteRole ( Role role )
                    {
                        Roles.DeleteRole( role.Name ) ;
                    }

                [Insert]
                public void AddRole ( Role role )
                    {
                        Roles.CreateRole( role.Name ) ;
                    }

                [Invoke( )]
                public void UpdateUserRoles ( string username, IEnumerable<string> userRoles )
                    {
                        string[] currentUserRoles = Roles.GetRolesForUser( username ) ;

                        var removedRoles = from r in currentUserRoles where userRoles.Contains( r ) == false select r ;

                        var newRoles = from r in userRoles where currentUserRoles.Contains( r ) == false select r ;

                        //Where Roles.IsUserInRole(r) = False

                        if ( newRoles.Count( ) > 0 )
                            Roles.AddUserToRoles( username, newRoles.ToArray( ) ) ;

                        if ( removedRoles.Count( ) > 0 )
                            Roles.RemoveUserFromRoles( username, removedRoles.ToArray( ) ) ;

                    }

                [Invoke( )]
                public void RemoveUserFromRole ( string username, string userRole )
                    {

                        if ( Roles.IsUserInRole( username, userRole ) )
                        {
                            Roles.RemoveUserFromRole( username, userRole ) ;

                        }

                    }

                [Invoke( )]
                public void AddUserToRole ( string username, string userRole )
                    {

                        if ( Roles.IsUserInRole( username, userRole ) == false )
                        {
                            Roles.AddUserToRole( username, userRole ) ;

                        }

                    }
            }
    }